//
//  HMService.swift
//  HealthMonitoring
//
//  Created by YTYanK on 30/03/2019.
//  Copyright © 2019 YTYanK. All rights reserved.
//

import UIKit
import SwiftyJSON


//public enum UserType: String {
//    case TypeDoctor = "Doctor"
//    case TypePatient = "Patient"
//}

public enum DataType: String {
    case TypeVisitPatient = "开始出诊"
    case TypeVisitDoctor = "医生服务"
}


class HMService: HMViewController {
    /// 数据列表
    var dataList = Array<Any>()
    /// 入口1
    var lattice1 = homeIconView()
    /// 人口2
    var lattice2 = homeIconView()
    /// 用户类型
    var dataType = DataType.TypeVisitDoctor
    /// 列表
    private lazy  var table: UITableView = {
        let _table = UITableView()
        _table.delegate = self
        _table.dataSource = self
        _table.register(HMSessionCell.classForCoder(), forCellReuseIdentifier: "HMSessionCell")
        _table.isHidden = true
        view.addSubview(_table)
        return _table
    }()
    
    /// 空数据背景
    private lazy var subViewNullData: UIView = {
        let subView = UIView.creatoreBgNullDataView(frame: CGRect.zero)
        view.addSubview(subView)
        return subView
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.requestData(dataType)
    }

    /// 获取列表数据
    func requestData(_ dataType: DataType) {
        
        NetRequestTool.shareInstance.met = .get
        var url = ""
        switch dataType {
        case .TypeVisitPatient:
            url = "doctor/consult/list"
        default:
            url = "user/consult/communicating"
        }
        
        
        NetRequestTool.request(url: url, parameters: [:], success: { (json) in
            let code = json["code"].intValue
            if code == 0 {
                self.dataList = json["data"].arrayValue
                if self.dataList.count > 0 {
                    self.table.reloadData()
                    self.table.isHidden = false
                }
            }else {
                //其他错误
                self.table.isHidden = true
            }
        }, fail: { (code, err) in
            print("报错:\(code)  err: -> \(err)")
        }) {
            
        }
    }
    
    override func setupView() {
        self.title = self.title(dataType)
        view.backgroundColor = configure.shareConfigure.HMColor2
       
        var iconAry:(Dictionary<String,String>, Dictionary<String, String>)
        switch dataType {
        case .TypeVisitDoctor:
            iconAry = (["png":"医生", "title": "健康咨询"],["png": "药物建议", "title": "药物建议"])
        default:
            iconAry = (["png":"weiBo", "title": "医生论坛"],["png": "药物建议", "title": "档案管理"])
        }
        self.setIcon(iconAry)
        
        self.subViewNullData.centerXYAlign(view: self.table)
        
        self.table.topVertically(view: self.lattice1, predicate: "\(2)")
        let h = view.wHeight - 120
        self.table.heightConstrain(predicate: "\(h)")
        self.table.leadingAlign(view: view, predicate: "0")
        self.table.trailingAlign(view: view, predicate: "0")

    }
    
    // 设置标题
    func title(_ dataType: DataType) -> String{
        switch dataType {
        case .TypeVisitPatient:
            return "开始出诊"
        default:
            return "医生服务"
        }
    }
    
    // 设置 icon\文字
    func setIcon(_ data: (Dictionary<String,String>, Dictionary<String, String>)) {
       
        let _lat1 = homeIconView()
        let _lat2 = homeIconView()
        view.addSubview(_lat1)
        view.addSubview(_lat2)

        let h = 120
        let topH = 2
        let w = (configure.shareConfigure.screenWidth/2) - 1
        
        _lat1.leadingAlign(view: view, predicate: "0")
        _lat1.topAlign(view: view, predicate: "\(topH)")
        _lat1.setData(imgName: data.0["png"]!, title: data.0["title"]!)
        _lat1.tag = 1110
        _lat1.delegate = self
        _lat1.heightConstrain(predicate: "\(h)")
        _lat1.widthConstrain(predicate: "\(w)")
        _lat1.backgroundColor = UIColor.white

        
        _lat2.leadingHorizontally(view: _lat1, predicate: "2")
        _lat2.topAlign(view: view, predicate: "\(topH)")
        _lat2.setData(imgName: data.1["png"]!, title: data.1["title"]!)
        _lat2.tag = 1111
        _lat2.delegate = self
        _lat2.heightConstrain(predicate: "\(h)")
        _lat2.widthConstrain(predicate: "\(w)")
        _lat2.backgroundColor = UIColor.white

        
        self.lattice1 = _lat1
        self.lattice2 = _lat2
        
    }
    
}


extension HMService: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 88
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = table.dequeueReusableCell(withIdentifier: "HMSessionCell") as! HMSessionCell
        cell.isTitleStr = self.title!
        if  self.dataType == .TypeVisitDoctor {
            cell.isDoctor = true
        }else {
            cell.isDoctor = false
        }
        
        cell.setJson(json: self.dataList[indexPath.row] as! JSON)
        cell.delegate = self
        cell.iconBlock = {
            (sessionCell) -> () in
//            print("购买")
            let patient = HMPatient()
            patient.dataJson =  (self.dataList[indexPath.row] as! JSON)
            patient.navigationController?.navigationBar.backgroundColor = .red
            self.pushViewController(patient)
        }
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cell = tableView.cellForRow(at: indexPath) as! HMSessionCell
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
        
        // 拿到对应的会话
        let dic = self.dataList[indexPath.row] as! JSON
        var _idStr = ""
        if  self.dataType == .TypeVisitDoctor {
              _idStr = dic["doctorId"].stringValue
              _im.im_consultId = dic["id"].stringValue
        }else {
             _idStr = dic["userId"].stringValue
             _im.im_consultId =  dic["consultId"].stringValue
        }
      
        let con :TIMConversation =   HMPlatform.getSomeoneConversation(_idStr)
        _im.conversation = con
        _im.im_doctorId = con.getReceiver()
      
        _im.userProfile = dic
        if cell.userProfile != nil {
            _im.doctorProfile = cell.userProfile!
        }
        _im.dataAry =   con.getLastMsgs(20)   //cell.messageList!
        self.pushViewController(_im)
    }
    
    
}

extension HMService: HMSessionCellDelegate {
    func sessionCellBtn(sender: UIButton, doctor: Bool) {

        let conId = sender.dictionary!["consultId"] as! String
        
        //医生邀请健康咨询
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "doctor/consult/invite", parameters: ["consultId": conId], success: { (json) in
            let code = json["code"].intValue
            if code == 0 {
                self.showToast(message: "邀请成功")
            }else {
                //其他错误
            }
            
            
        }, fail: { (code, err) in
            print("=====>",code, err)
        }) {
            
        }
    }
}

extension HMService: homeIconViewDelegate {
    func viewTapClick(view: UIView) {
        if self.dataType == .TypeVisitDoctor {
            if view.tag == 1110 {
                // 健康咨询
            }else {
                // 药方建议
                
            }
        }else  {
            if view.tag == 1110 {
               //医生论坛
            }else {
                let drug = HMProposalDrug() // 档案管理
                drug.info = ["sign": "档案管理"]
                drug.title = "档案管理"
                drug.variableTitles = ["药方管理", "咨询设置"]
                let twoVc = HMDrugStencil() //HMProposalAll()
                twoVc._signStr = "医生出诊"//
                twoVc.dataType = self.dataType
//                let twoVc = HMDrugStencil()
//                twoVc._signStr = "医生出诊"
//                twoVc.dataType = self.dataType
//                self.pushViewController(twoVc)
//                twoVc.titleSign = "医生出诊"
                let threeVc = HMAdvisorySetting()
                drug.variableControllers = [twoVc, threeVc]
                self.pushViewController(drug)
                
            }
        }
      
    }
    
    
}
